package com.jshan.blog.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jshan.blog.base.admin.dto.LoginAndRegisterDto;
import com.jshan.blog.base.admin.entity.SysUser;
import com.jshan.blog.constans.AuthUserInfoConst;
import com.jshan.blog.converts.SysUserAndDtoConvert;
import com.jshan.blog.enums.AccountStatusEnum;
import com.jshan.blog.service.SysRoleMenuService;
import com.jshan.blog.service.SysUserService;
import com.jshan.blog.mapper.SysUserMapper;
import com.jshan.blog.utils.BcyEncodingUtil;
import com.jshan.blog.utils.RedisUtil;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author jshan
 * @description 针对表【sys_user(系统用户表)】的数据库操作Service实现
 * @createDate 2025-01-16 16:47:01
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
        implements SysUserService {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    @Lazy
    private SysRoleMenuService roleMenuService;


    @Override
    public Boolean saveDto(LoginAndRegisterDto loginAndRegisterDto) {
        SysUser user = SysUserAndDtoConvert.INSTANCE.LoginDto2UserConvert(loginAndRegisterDto);
        user.setPwd(BcyEncodingUtil.bcyEncode(loginAndRegisterDto.getPwd()));
        user.setCreateTime(LocalDateTime.now());
        return this.save(user);
    }

    @Override
    public Map<Object, Object> doLogin(LoginAndRegisterDto loginAndRegisterDto) {
        Map<Object, Object> map = new HashMap<>();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        // 根据登录的用户名获取用户相关信息
        SysUser userInfo = this.getOne(wrapper.eq(SysUser::getUsername, loginAndRegisterDto.getUsername()));
        // 没有查询到相关信息 直接返回
        if (ObjectUtils.isEmpty(userInfo)) {
            return null;
        }
        // 密码比较 密码不对直接返回
        if (!BcyEncodingUtil.checkPwd(loginAndRegisterDto.getPwd(), userInfo.getPwd())) {
            return null;
        }
        if (!Objects.equals(userInfo.getAccountStatusCd(), AccountStatusEnum.ACCOUNT_NORMAL.getCode())) {
            return null;
        }

        userInfo.setLastLoginTime(LocalDateTime.now());
        this.updateById(userInfo);

        String key = AuthUserInfoConst.USER_INFO_KEY + userInfo.getId();
        redisUtil.setValue(key, JSON.toJSONString(userInfo));
        StpUtil.login(userInfo.getId());
        map.put("userId", userInfo.getId());
        map.put("username", userInfo.getUsername());
        map.put("nickname", userInfo.getNickname());
        map.put("tokenInfo", StpUtil.getTokenInfo().tokenValue);
        // 将用户的权限或者用户所在role的权限保存到redis中
        String authInfoKey = AuthUserInfoConst.AUTH_INFO_KEY + userInfo.getId();
        Set<String> permission = roleMenuService.listPermAll(userInfo.getUserTagCd());
        if (CollectionUtils.isNotEmpty(permission)) {
            redisUtil.setValue(authInfoKey, JSON.toJSONString(permission));
        }
        return map;
    }

    @Override
    public Boolean saveUserInfo(SysUser user) {
        SysUser one = this.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, user.getUsername()));
        if (ObjectUtils.isEmpty(one)) {
            user.setPwd(BcyEncodingUtil.bcyEncode(user.getPwd()));
            user.setCreateTime(LocalDateTime.now());
            user.setCreateId(StpUtil.getLoginIdAsInt());
            return this.save(user);
        }
        return false;
    }

    /**
     * 获取用户信息 右上角的图像
     *
     * @param userId
     * @return
     */
    @Override
    public SysUser getUserInfoById(Integer userId) {
        return baseMapper.getUserInfoById(userId);
    }
}




